<template>
  <div>
    <el-form size="mini"
             :model="contractapprove"
             label-width="110px"
             label-position="left">
      <el-row>
        <el-col :span="8">
          <el-form-item label="项目名称">
            <el-input :readonly="current == 0 ? false : true"
                      clearable
                      v-model="contractapprove.manage_contractapprove_name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属公司">
            <el-select v-model="contractapprove.manage_contractapprove_company">
              <el-option v-for="(item, index) in companyList"
                         :key="index"
                         :value="item[0]"
                         :label="item[1]"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目地址">
            <el-input :readonly="current == 0 ? false : true"
                      clearable
                      v-model="contractapprove.manage_contractapprove_address"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="发包方（甲方）">
            <el-input :readonly="current == 0 ? false : true"
                      clearable
                      v-model="contractapprove.manage_contractapprove_firstParty"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发包方税号">
            <el-input :readonly="current == 0 ? false : true"
                      clearable
                      v-model="contractapprove.manage_contractapprove_taxNumber"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同金额">
            <el-input :readonly="current == 0 ? false : true"
                      clearable
                      type="number"
                      v-model="contractapprove.manage_contractapprove_amount"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="乙方">
            <el-input :readonly="current == 0 ? false : true"
                      clearable
                      v-model="contractapprove.manage_contractapprove_secondParty"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="开始时间">
            <el-date-picker v-model="contractapprove.manage_contractapprove_startTime"
                            type="date"
                            :readonly="current == 0 ? false : true"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择时间"
                            style="width:100%;">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结束时间">
            <el-date-picker :readonly="current == 0 ? false : true"
                            v-model="contractapprove.manage_contractapprove_endTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择时间"
                            style="width:100%;">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="面积及使用性质">
            <el-input :readonly="current == 0 ? false : true"
                      clearable
                      v-model="contractapprove.manage_contractapprove_area"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="付款比例">
            <el-input :readonly="current == 0 ? false : true"
                      clearable
                      v-model="contractapprove.manage_contractapprove_payment"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="付款方式">
            <el-input :readonly="current == 0 ? false : true"
                      clearable
                      v-model="contractapprove.manage_contractapprove_paymentMethod"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="工程内容">
            <el-checkbox-group v-model="contractapprove.manage_contractapprove_content"
                               :disabled="current == 0 ? false : true">
              <el-checkbox v-for="(item, index) in category"
                           :label="index + 1"
                           :key="index">{{ item }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否报建">
            <el-radio-group v-model="contractapprove.manage_contractapprove_report"
                            size="mini"
                            :disabled="current == 0 ? false : true">
              <el-radio label="1"
                        border>是</el-radio>
              <el-radio label="2"
                        border>否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="是否含税">
            <el-radio-group v-model="contractapprove.manage_contractapprove_taxIncluded"
                            size="mini"
                            :disabled="current == 0 ? false : true">
              <el-radio :label="1"
                        border>含税专票</el-radio>
              <el-radio :label="2"
                        border>含税普票</el-radio>
              <el-radio :label="3"
                        border>不含税</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="合同类型">
            <el-radio-group v-model="contractapprove.category"
                            size="mini"
                            @change="getProcessline"
                            :disabled="current == 0 ? false : true">
              <el-radio :label="1"
                        border>施工合同</el-radio>
              <el-radio :label="2"
                        border>供应商合同</el-radio>
              <el-radio :label="3"
                        border>合作合同</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注">
        <el-input :readonly="current == 0 ? false : true"
                  clearable
                  type="textarea"
                  :rows="2"
                  v-model="contractapprove.manage_contractapprove_remark"></el-input>
      </el-form-item>
      <el-form-item label="意见"
                    v-if="openType === 'headle'">
        <el-input clearable
                  type="textarea"
                  :rows="3"
                  v-model="reasons"></el-input>
      </el-form-item>
      <el-row>
        <template v-if="userTaskName != '结束' && openType != 'check'">
          <el-col :span="10">
            <el-form-item label="下一节点">
              <el-input readonly
                        v-model="userTaskName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="审核人">
              <el-select v-model="userid">
                <el-option v-for="(item, index) in userList"
                           :key="index"
                           :value="item.userid"
                           :label="item.username"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </template>

        <el-col :span="24"
                v-if="openType == 'add'">
          <el-form-item label=" ">
            <el-button style="margin-left: 10px;"
                       size="mini"
                       type="success"
                       @click="submit">提交</el-button>
          </el-form-item>
        </el-col>

        <template v-else-if="openType == 'headle'">
          <el-form-item label=" ">
            <el-col :span="16">
              <el-upload style="float:left; margin-right:10px;"
                         ref="upload"
                         :action="upload_url"
                         :limit="1"
                         :on-change="handleChange"
                         :headers="{ token: token }"
                         :on-success="handleSuccess"
                         :on-error="headleError"
                         v-if="current == 1">
                <el-button slot="trigger"
                           type="primary"
                           size="mini">选取文件</el-button>
              </el-upload>
              <el-button type="primary"
                         size="mini"
                         @click="openfile"
                         v-if="
                  contractapprove.manage_contractapprove_attachAddress != '' &&
                    contractapprove.manage_contractapprove_attachAddress
                ">
                下载附件
              </el-button>
              <template v-for="(item, index) in buttonList">
                <el-button v-if="item == 'submit'"
                           :key="index"
                           type="success"
                           size="mini"
                           @click="headleprocess(true)">提交</el-button>
                <el-button v-if="item == 'Resubmit'"
                           :key="index"
                           type="success"
                           size="mini"
                           @click="headleprocess(true)">重新提交</el-button>
                <el-button v-else-if="item == 'reject'"
                           :key="index"
                           type="warning"
                           size="mini"
                           @click="headleprocess(false)">驳回</el-button>
                <el-button v-else-if="item == 'disagree'"
                           :key="index"
                           type="danger"
                           size="mini"
                           @click="headleprocess('finish')">不同意</el-button>
              </template>
            </el-col>
          </el-form-item>
        </template>
      </el-row>
    </el-form>
    <el-divider content-position="left">流程线</el-divider>
    <el-steps :active="current"
              finish-status="success"
              align-center>
      <el-step :title="item.name"
               v-for="(item, index) in activityList"
               :key="index"></el-step>
    </el-steps>
    <template v-if="openType !== 'add'">
      <el-divider content-position="left">审批流程</el-divider>
      <el-table :data="history"
                border="">
        <el-table-column v-for="(item, index) in HeaderList"
                         :key="index"
                         :label="item[0]"
                         :prop="item[1]"
                         :type="index == 0 ? 'index' : ''"
                         :width="item[2]"
                         align="center"></el-table-column>
      </el-table>
    </template>
  </div>
</template>

<script>
import http from "@/request/http.js";
import {
  apisave_conApprove,
  apiContractapprovePro,
  apicontractapprovePass
} from "@/request/api.js";
export default {
  name: "dialogWindow",
  data () {
    return {
      upload_url: http.base_url + "uploadContractFile",
      token: sessionStorage.getItem("token"),
      HeaderList: [
        ["序号", ""],
        ["步骤名称", "name_"],
        ["相关人员", "username"],
        ["开始时间", "START_TIME_"],
        ["结束时间", "END_TIME_"],
        ["审核意见", "MESSAGE_"],
        ["内容", ""]
      ],
      category: [
        "自动报警系统",
        "防排烟系统",
        "自动喷淋系统",
        "应急照明及疏散指示",
        "配置灭火器"
      ],
      companyList: [
        [1, "建设公司"],
        [2, "科技公司"],
        [3, "加盟合作"],
        [4, "诚安教育"],
        [5, "传诚管理"]
      ],
      buttonList: [],
      userid: 0,
      current: 0,
      userLists: [],
      userList: [],
      activityList: [],
      activityLists: [],
      reasons: "",
      fileList: [],
      userTaskName: ""
    };
  },
  props: {
    contractapprove: Object,
    active: Object,
    history: Array,
    openType: String
  },
  created () {
    console.log(this.contractapprove)
    this.getprossList();
  },
  methods: {
    //打开附件
    openfile () {
      window.open(this.contractapprove.manage_contractapprove_attachAddress);
    },
    //办理
    headleprocess (type) {
      if (this.reasons == "") {
        this.$message.error("请填写审核意见");
        return;
      }
      if (this.userid === "" && type) {
        this.$message.error("审核人为空不能提交！");
        return;
      }
      this.contractapprove.manage_contractapprove_content = JSON.stringify(
        this.contractapprove.manage_contractapprove_content
      );
      this.contractapprove.taskid = this.active.ID_;
      this.contractapprove.userid = this.userid;
      this.contractapprove.reason = this.reasons;
      this.contractapprove.type = type;
      console.log(this.contractapprove);
      this.$confirm(`确定提交吗？`)
        .then(() => {
          apicontractapprovePass(this.contractapprove).then(res => {
            console.log(res);
            this.$message.success(res.Msg);
            this.$emit("close");
          });
        })
        .catch(() => { });
    },
    getProcessline (val) {
      // 三目运算判定合同类型，获取流程线中的字段名
      let processName =
        val == 1 ? "process0" : val == 2 ? "process1" : "process2";
      //当审批记录存在时，遍历更改时间格式
      this.activityList = this.activityLists[processName];
      if (this.history != "") {
        let currentTask = this.history[this.history.length - 1];
        this.activityList.forEach((item, index) => {
          if (item.name == currentTask.name_) {
            this.current = currentTask.END_TIME_ == "" ? index : index + 1;
          }
        });
      }
      // 在新增时，根据合同类型选择流程走向
      if (this.openType == "add") {
        this.userList = this.userLists[val].userList;
        // 获取下一节点名称
        this.userTaskName = this.userLists[val].userTaskName;
        // 获取用户ID
        this.userid = this.userList ? this.userList[0].userid : "";
      } else {
        // 办理时，按固定的流程线走
        this.userList = this.userLists.userList;
        // 获取下一节点名称
        this.userTaskName = this.userLists.userTaskName;
        // 获取用户ID
        this.userid = this.userList ? this.userList[0].userid : "";
      }
    },
    //获取流程线
    getprossList () {
      let data = {};
      if (this.active) {
        data = {
          key: "contractapproveView", //流程定义KEY
          taskid: this.active.ID_, //(必填)流程任务id
          processInstanceId: this.active.PROC_INST_ID_
            ? this.active.PROC_INST_ID_
            : this.active.taskid, //(必填)流程实例id
          type: "" //(必填)新增new/运行中
        };
      } else {
        data = {
          key: "contractapproveView", //流程定义KEY
          taskid: "", //(必填)流程任务id
          processInstanceId: "", //(必填)流程实例id
          type: "new" //(必填)新增new/运行中
        };
      }

      apiContractapprovePro(data).then(res => {
        console.log(res);
        // 获取流程线
        this.activityLists = res.activityList;
        this.userLists = res.userlist;
        // 切割办理按钮
        this.buttonList = res.startForm.split(",");
        // 根据默认合同类型获取流程线
        this.getProcessline(this.contractapprove.category);
      });
    },

    //文件上传前的钩子
    handleChange (file, fileList) {
      console.log(file);
      this.fileList = fileList.map(item => {
        return item.name;
      });
    },

    handleSuccess (res, file, fileList) {
      // 文件上传成功的回调，获取合同路径，再运行submit（）进行提交
      this.contractapprove.manage_contractapprove_attachAddress = res.data;
      // this.submit();
    },

    // 上传文件失败的回调函数
    headleError (err, file, fileList) {
      console.log(err);
    },

    submitUpload () {
      //当没有附件时单独提交
      if (this.fileList == "") {
        this.submit();
      } else {
        this.$refs.upload.submit();
      }
    },

    // 提交
    submit () {
      this.contractapprove.manage_contractapprove_content = JSON.stringify(
        this.contractapprove.manage_contractapprove_content
      );
      this.contractapprove.userid = this.userid;
      console.log(this.contractapprove);
      this.$confirm(`确定提交吗？`)
        .then(() => {
          apisave_conApprove(this.contractapprove).then(res => {
            this.$message.success(res.msg);
            this.$emit("closewin");
          });
        })
        .catch(() => { });
    },

    //从子组件中获取下一审核人ID
    getSpprover (userid) {
      this.contractapprove.userid = userid;
    }
  }
};
</script>

<style lang="scss" scoped></style>
